package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.dao.TaskDao2;
import com.lkd.dao.TaskDetailsDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.*;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;

    @Autowired
    private TaskDetailsDao taskDetailsDao;

    @Autowired
    private TaskDao2 taskDao2;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {

        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    /**
     * 新增工单
     *
     * @param taskViewModel
     * @return boolean
     */

    private void checkHasTodoTask(TaskViewModel taskViewModel){
        //判断是否有未完成的工单
        LambdaQueryWrapper<TaskEntity> le = Wrappers.<TaskEntity>lambdaQuery()
                .eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode())
                .eq(TaskEntity::getProductTypeId, taskViewModel.getProductType())
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        if (count(le) > 0) {
            throw new LogicException("工单创建失败，当前售货机有未完成工单!");
        }
    }

    private void checkVmStatusAndTaskType(VmVO info,int productType){
        //如果innercode不存在 debug会不会出错
        if(info == null){
            throw new LogicException("售货机不存在!");
        }

        //（1）如果是补货工单，状态不是运营状态，抛出异常
        if (VMSystem.TASK_TYPE_SUPPLY == productType
                && !Objects.equals(info.getVmStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机未运营!");
        }

        // （2）如果是投放工单，状态为运营，抛出异常
        if (VMSystem.TASK_TYPE_DEPLOY == productType
                && Objects.equals(info.getVmStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机运营中，无法投放!");
        }
        //（3）如果是撤机工单，状态不是运营状态，抛出异常
        if (VMSystem.TASK_TYPE_REVOKE == productType
                && !Objects.equals(info.getVmStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机未运营!");
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(TaskViewModel taskViewModel) {

        //判断是否有未完成的工单
        checkHasTodoTask(taskViewModel);

        VmVO info = vmService.getVMInfo(taskViewModel.getInnerCode());

        //校验售货机状态和工单类型是否匹配
        checkVmStatusAndTaskType(info,taskViewModel.getProductType());

        TaskEntity taskEntity = new TaskEntity();
        //拷贝对象至TaskEntity
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        //设置售货机信息
        taskEntity.setRegionId(info.getRegionId());
        taskEntity.setAddr(info.getNodeAddr());

        //工单类型 1234 字段名不同需要手动拷贝
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //生成订单编号
        String taskCode = generateTaskCode();
        //设置订单编号到taskEntity
        taskEntity.setTaskCode(taskCode);

        //设置用户信息
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user == null){
            throw new LogicException("执行人不存在!");
        }
        taskEntity.setUserName(user.getUserName());

        //保存工单
        save(taskEntity);
        //补货工单才需要处理补货详情
        if (VMSystem.TASK_TYPE_SUPPLY == taskViewModel.getProductType()) {
            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            if(!CollectionUtils.isEmpty(details)){
                for (TaskDetailsViewModel detail : details) {
                    TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                    BeanUtils.copyProperties(detail,taskDetailsEntity);
                    taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                    taskDetailsService.save(taskDetailsEntity);
                }
            }
        }
        //创建工单时给人员工单量进行加1
        changeUserTaskCount(taskEntity.getUserId(),1);
        return true;
    }

    //修改人员工单量
    private void changeUserTaskCount(Integer userId,int add){
        //更新redis中的工单量
        UserVO user = userService.getUser(userId);
        //String roleCode = Objects.equals(task.getProductTypeId(), VMSystem.TASK_TYPE_SUPPLY)?"1002":"1003";
        String key = VMSystem.generateUserTaskCount(user.getRoleCode(),user.getRegionId());
        redisTemplate.opsForZSet().incrementScore(key,userId,add);
    }

    @Override
    public boolean accept(TaskEntity task) {
        if(!Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_CREATE)){
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        if(Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_FINISH) ||
                Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_CANCEL)){
            throw new LogicException("工单已经结束");
        }

        if(Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_PROGRESS)){
            changeUserTaskCount(task.getUserId(),-1);
        }

        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if(taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_FINISH  || taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }

        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);

        //修改工单量
        changeUserTaskCount(taskEntity.getUserId(),-1);

        //投放 工单 售货机 未投放 -> 运营
        //撤机 运营 ->未投放
        //维修？
        //补货工单 -> 将货道中库存进行更新
        if(Objects.equals(taskEntity.getProductTypeId(), VMSystem.TASK_TYPE_DEPLOY)
         || Objects.equals(taskEntity.getProductTypeId(), VMSystem.TASK_TYPE_REVOKE)){
            //发送运维工单消息
            this.noticeOperationTask(taskEntity);
        }else if(Objects.equals(taskEntity.getProductTypeId(), VMSystem.TASK_TYPE_SUPPLY)){
            this.noticeSupplyTask(taskEntity);
        }
        return true;
    }

    @Override
    public Integer getLeastUser(Long regionId, boolean isReparing) {
        String roleCode = isReparing? "1003" : "1002" ;
        String key =  VMSystem.generateUserTaskCount(roleCode,regionId);
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 0);
        if(CollectionUtils.isEmpty(range)){
            return null;
        }
        return (Integer) new ArrayList<>(range).get(0);
    }

    //通过日期统计工单数 taskType = 0 运营工单 taskType = 1 运维工单
    private Integer countTaskStatusByDate(LocalDateTime start, LocalDateTime end,Integer taskStatus,int taskType){
        return taskDao2.countTaskStatusByDate(start,end,taskStatus,taskType);
    }

    @Override
    public List<TaskReportInfoVO> taskReportInfo(LocalDateTime start, LocalDateTime end) {

        List<TaskReportInfoVO> taskReportInfoVOS = new ArrayList<>();
        //将end日期加1天 7-27
        end = end.plusDays(1);

        //运营工单
        TaskReportInfoVO vo1 = new TaskReportInfoVO();
        vo1.setCancelTotal(countTaskStatusByDate(start,end,VMSystem.TASK_STATUS_CANCEL,0));
        vo1.setCompletedTotal(countTaskStatusByDate(start,end,VMSystem.TASK_STATUS_FINISH,0));
        vo1.setProgressTotal(countTaskStatusByDate(start,end,VMSystem.TASK_STATUS_PROGRESS,0));
        vo1.setTotal(countTaskStatusByDate(start,end,null,0));
        vo1.setRepair(false);
        vo1.setWorkerCount(userService.getOperatorCount());
        vo1.setDate(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        taskReportInfoVOS.add(vo1);

        TaskReportInfoVO vo2 = new TaskReportInfoVO();
        vo2.setCancelTotal(countTaskStatusByDate(start,end,VMSystem.TASK_STATUS_CANCEL,1));
        vo2.setCompletedTotal(countTaskStatusByDate(start,end,VMSystem.TASK_STATUS_FINISH,1));
        vo2.setProgressTotal(countTaskStatusByDate(start,end,VMSystem.TASK_STATUS_PROGRESS,1));
        vo2.setTotal(countTaskStatusByDate(start,end,null,1));
        vo2.setRepair(true);
        vo2.setWorkerCount(userService.getRepairerCount());
        vo2.setDate(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        taskReportInfoVOS.add(vo2);

        return taskReportInfoVOS;
    }

    @Override
    public List<UserWorkVO> getUserWorkTop10(LocalDate start, LocalDate end, Boolean isRepair, Long regionId) {
        Page<UserWorkVO> page = new Page<>();
        page.setCurrent(1);
        page.setSize(10);
        page.setSearchCount(false);//避免执行count select 数据 select count 统计所有条数
        return taskDao2.getUserWorkTop10(page,start,end.plusDays(1),isRepair?1:0,regionId).getRecords();
    }

    /**
     * 按时间和状态进行统计
     * @param start
     * @param taskStatus
     * @return
     */
    private int count(LocalDate start ,Integer taskStatus){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,start.plusDays(1))
                .eq(TaskEntity::getTaskStatus, taskStatus);
        return this.count(qw);
    }

    @Override
    public List<TaskCollectVO> getTaskReport(LocalDate start, LocalDate end) {
        List<TaskCollectVO> taskCollectVOList= Lists.newArrayList();
        //从开始日期到截至日期，逐条统计
//        List<LocalDate> collect = start.datesUntil(end.plusDays(1), Period.ofDays(1)).collect(Collectors.toList());
//        for (LocalDate localDate : collect) {
//
//        }

        start.datesUntil(end.plusDays(1), Period.ofDays(1))
                .forEach(date->{
                    var taskCollectVO=new TaskCollectVO();
                    taskCollectVO.setCollectDate(date);
                    taskCollectVO.setProgressCount(count(date,VMSystem.TASK_STATUS_PROGRESS )); //进行中工单数
                    taskCollectVO.setFinishCount(count(date,VMSystem.TASK_STATUS_FINISH ));//完成工单数
                    taskCollectVO.setCancelCount(count(date,VMSystem.TASK_STATUS_CANCEL ));//取消工单数
                    taskCollectVOList.add(taskCollectVO);
                });
        return taskCollectVOList;
    }

    //补货消息
    private void noticeSupplyTask(TaskEntity taskEntity) {

        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        ArrayList<SupplyChannel> supplyChannels = new ArrayList<>();
        supplyContract.setSupplyData(supplyChannels);

        List<TaskDetailsEntity> taskDetailsEntities =
                taskDetailsDao.selectList(Wrappers.<TaskDetailsEntity>lambdaQuery()
                .eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId()));

        //判断详情为空
        if(CollectionUtils.isEmpty(taskDetailsEntities)){
            log.info("补货详情为空:taskId{}",taskEntity.getTaskId());
            return;
        }

        for (TaskDetailsEntity taskDetailsEntity : taskDetailsEntities) {
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
            supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
            supplyContract.getSupplyData().add(supplyChannel);
        }

        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyContract);
        } catch (JsonProcessingException e) {
            throw new LogicException("发送时对象转json失败");
        }
    }

    //运维消息
    public void noticeOperationTask(TaskEntity taskEntity){
        TaskCompleteContract contract = new TaskCompleteContract();
        contract.setTaskType(taskEntity.getProductTypeId());
        contract.setInnerCode(taskEntity.getInnerCode());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,contract);
        } catch (JsonProcessingException e) {
           throw new LogicException("发送时对象转json失败");
        }
    }
}
